package com.xt;

import java.awt.Frame;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;

/**
 * @author v_guiqtong
 * @version 1.0
 */
public  class  HookListener<T extends NativeMouseInputListener> implements NativeMouseInputListener{

    private MouseSelectData mouseSelectData;

    private Frame frame;

    private T t;

    @Override
    public void nativeMouseClicked(NativeMouseEvent nativeMouseEvent) {
    }

    @Override
    public void nativeMousePressed(NativeMouseEvent nativeMouseEvent) {
        mouseSelectData.setStartPoint(nativeMouseEvent.getPoint());
    }

    @Override
    public void nativeMouseReleased(NativeMouseEvent nativeMouseEvent) {
        mouseSelectData.setEndPoint(nativeMouseEvent.getPoint());
        mouseSelectData.calculate();
        GlobalScreen.removeNativeMouseListener(t);
        GlobalScreen.removeNativeMouseMotionListener(t);
        try {
            GlobalScreen.unregisterNativeHook();
        } catch (NativeHookException e) {
            throw new RuntimeException(e);
        }
        frame.setState(Frame.NORMAL);
    }

    @Override
    public void nativeMouseMoved(NativeMouseEvent nativeMouseEvent) {
    }

    @Override
    public void nativeMouseDragged(NativeMouseEvent nativeMouseEvent) {

    }


    public MouseSelectData start(T t, Frame frame) {
        this.frame = frame;
        this.mouseSelectData = new MouseSelectData();
        try {
            GlobalScreen.registerNativeHook();
        } catch (Exception e) {
            return null;
        }
        GlobalScreen.addNativeMouseListener(t);
        GlobalScreen.addNativeMouseMotionListener(t);
        while (true) {
            if (this.frame.getState()==Frame.NORMAL) {
                break;
            }
        }
        return mouseSelectData.deepCopy();
    }
}
